<?php
/*  This is my attempt at creating a class file.  I know we were suposed to keep it dimple, but this 
is the most simple way I know how to program.  I guess once you are an object oriented programmer, you always lean toward
objects, */
class Blog{
	//Declare the member variables of the class.  These basically relate to the form and the DB
	public $id;
	public $title;
	public $body;

	//This is a constructor.  I will pass an array to this constructor, and it will take the items out of the array and put them on this object
	//If I did thid correct, I will be able to construct a contact from either a DB result array, or a post array.
	public function __construct($anyArray){
		//echo "In the constructor";
		if($anyArray){
			$this->id = $anyArray['id'];
			$this->title = $anyArray['title'];
			$this->body = $anyArray['body'];
		}
	}
	
	//This is what will add a new blog into the DB.  I will pass the connection to this function so I can use it if it has been declared after this class is read by php
	public function add($dbh){
		//echo "in the add function";
		//echo "Adding a new blog to the DB";
		$sql = "INSERT INTO blog (title, body) VALUES ( ". $dbh->quote($this->title) ." , ". $dbh->quote($this->body) .")";
		//echo "$sql";
		$dbh->exec($sql);
	}

	//This will update the db with the values on this instance.
	public function update($dbh){
		//echo "in the update function";
		$sql = "UPDATE blog SET title=". $dbh->quote($this->title) .", body=". $dbh->quote($this->body) ."  WHERE id=". $dbh->quote($this->id);
		//echo "$sql";
		return $dbh->exec($sql);
	}

	//I will use this function to remove records from the DB
	public function delete($dbh){
		//echo "in the delete function";
		$sql = "DELETE FROM blog WHERE id=". $dbh->quote($this->id);
		return $dbh->exec($sql);
	}
	
	//This will return a list of all of the blogs
	public function getAll($dbh){
		//echo "in the get all function";
		$sql = "SELECT id, title, body FROM blog";
		return $dbh->query($sql)->fetchAll();
		
	}

	//This function will get one blog from the DB for the given ID
	public function getOneBlog($dbh, $dbId){
		//echo "In the get One Blog function for ID: $dbId";
		$sql = "SELECT id, title, body FROM blog WHERE id = " . $dbh->quote($dbId);
		$row =  $dbh->query($sql)->fetch();
		$this->id = $row['id'];
		$this->title = $row['title'];
		$this->body = $row['body'];
		return $this;
		//echo "Found blog with title: $this->title";
	}
}
?>
